<template>
  <div class="home ml-1 mr-1 md-1">
    <Header @errMsg="setSnackBarFalse" @successMsg="setSnackBarTrue" ref="header"/>
    <button class="toggle-button" :class="{ show: isSidebarVisible }" @click="toggleSidebar">☰</button>
    <div class="main-content">
      <Sidebar class="sidebar" @item-selected="changeContent" ref="sb" :class="{ show: isSidebarVisible }"/>
      <div style="background-color:#ededed; padding: 10px;width: 100%;height: 100%; border-bottom-right-radius: 10px">
        <component :key="cpnKey" :is="currentContentComponent"
                   @refresh="refresh" @errMsg="setSnackBarFalse"
                   @successMsg="setSnackBarTrue" @sendData="sendData"
                   @getData="transportData" @showConn="showStatusAlert"
                   ref="cpn" style="background-color:#ffffff;"/>
      </div>
      <div class="overlay" :class="{overlay2 : isSidebarVisible}" @click="isSidebarVisible=false"></div>
    </div>
<!--     广告预留接口-->
<!--        <v-carousel class="ad-carousel" height="100" cycle interval="5000" hide-delimiters>-->
<!--          <v-carousel-item v-for="(image, index) in images" :key="index">-->
<!--            <v-img :src="image" class="fill-height" contain></v-img>-->
<!--          </v-carousel-item>-->
<!--        </v-carousel>-->
    <v-snackbar
        v-model="snackbar.show"
        :color="snackbar.color"
        :timeout="1500"
        multi-line
        top
    >
      <template>
        <v-icon v-if="snackbar.icon" :color="snackbar.iconColor">{{ snackbar.icon }}</v-icon>
      </template>
      {{ snackbar.text }}
      <v-spacer></v-spacer>
    </v-snackbar>
    <v-dialog v-model="dialog" max-width="400" persistent>
      <v-card>
        <v-card-title class="headline">{{ title }}</v-card-title>

        <v-card-text :key="status">
          <div v-if="status === 2" :key="status" class="text-center">
            <v-progress-circular indeterminate color="primary"></v-progress-circular>
            <p>{{ message }}</p>
          </div>
          <div v-if="status === 1" :key="status" class="text-center">
            <v-icon large color="error">mdi-close-circle</v-icon>
            <p>连接失败, {{ message }}</p>
          </div>
          <div v-if="status === 0" :key="status" class="text-center">
            <v-icon large color="success">mdi-check-circle</v-icon>
            <p>连接成功, 当前可用数据传输的串口有<br> {{ message }}</p>
          </div>
        </v-card-text>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="green darken-1" text v-if="status !== 2" @click="dialog = false">确定</v-btn>
          <v-btn color="green darken-1" text v-if="status === 2" @click="dialog = false">关闭</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import Header from '@/components/Header-component.vue'
import Sidebar from '@/components/Sidebar-component.vue'
import RegisterDeviceContent from "@/components/RegisterDeviceContent.vue";
import SystemInformationContent from "@/components/SystemInformationContent.vue";
import SerialSettingsContent from "@/components/SerialSettingsContent.vue";
import SearchingDeviceContent from "@/components/SearchingDeviceContent.vue";
import WIFISettingsContent from "@/components/WIFISettingsContent.vue";
import MonitorContent from "@/components/MonitorContent.vue";

const resultSuccessCode = [
  "n2n连接中", "n2n已连接", "本地连接设备成功"
];
const resultErrCode = [
  "本地连接设备失败"
];

export default {
  created() {
    this.$refresh();
    this.setupListener();
  },
  mounted() {
    this.setReceiveDataFromServerListener(); // 获取设备返回的数据
    this.setSendDataCallbackListener(); // 监听设备未连接事件
    this.setConnRemoteCallbackListener(); // 监听远程连接设备结果事件
    this.setConnectServerCallbackListener(); // 获取连接设备的返回值
    window.addEventListener('resize', this.checkWindowWidth);
    this.checkWindowWidth(); // 初始化时检查窗口宽度
  },
  beforeDestroy() {
    // window.electronAPI.disconnectRemote();
    const data = {
      "cmd": 244,
      'config': {
        'portmap': this.deviceInfo.portmap
      }
    }
    window.electronAPI.sendSettings(JSON.stringify(data));
    window.electronAPI.removeAllEvent();
    localStorage.removeItem('sn');

    window.removeEventListener('resize', this.checkWindowWidth);
  },
  name: 'Home-component',
  components: {
    Header,
    Sidebar,
    WIFISettingsContent,
    SerialSettingsContent,
    RegisterDeviceContent,
    SystemInformationContent,
    SearchingDeviceContent,
    MonitorContent
  },
  data() {
    return {
      currentContentComponent: 'WIFISettingsContent',
      connected: false,
      snackbar: {
        show: false,
        color: '',
        text: '',
        icon: '',
        iconColor: ''
      },
      deviceInfo: '',
      portInfo: [],
      cpnKey: 0,
      status: 2,
      dialog: false,
      title: '',
      message: '',
      ip: '',
      images: [
        'https://ts1.cn.mm.bing.net/th/id/R-C.1c05de0609916e40f72cdc9669ee4d09?rik=%2f%2f1f3nZ5GJrdjQ&riu=http%3a%2f%2fweknowyourdreams.com%2fimages%2fhappy%2fhappy-06.jpg&ehk=eCiuP1pMTtYeV2q8MpK3C5Vm0l2ValarKRDdIfZzjpY%3d&risl=&pid=ImgRaw&r=0',
        'https://is2-ssl.mzstatic.com/image/thumb/Music124/v4/38/9f/09/389f0965-2f8d-212d-0e4b-de951e45344a/093624888703.jpg/1200x1200bf-60.jpg',
        'https://ts1.cn.mm.bing.net/th/id/R-C.a88b604ae73a3755df72db1b50447645?rik=2OVKuSoOBzKSBA&riu=http%3a%2f%2fst.depositphotos.com%2f1000128%2f4721%2fi%2f450%2fdepositphotos_47218435-stock-photo-happy-yellow-smileys.jpg&ehk=SeM9qG5gE2vABxHzEG6L4obo4llxJycYM4Zg38o6X9w%3d&risl=&pid=ImgRaw&r=0'
      ],
      networkRequest: {
        "cmd": 251
      },
      wifiRequest: {
        "cmd": 252
      },
      strengthId: '',
      wifiId: '',
      wifiList: [],
      isSidebarVisible: false,
    }
  },
  methods: {
    changeContent(selectedItem) {
      this.$refresh();
      switch (selectedItem) {
        case 'WIFI设置':
          this.currentContentComponent = 'WIFISettingsContent';
          setTimeout(() => {
            this.transportData(selectedItem);
          }, 500);
          break;
        case '端口设置':
          this.currentContentComponent = 'SerialSettingsContent';
          setTimeout(() => {
            this.transportData(selectedItem);
          }, 500)
          break;
        case '注册设备':
          this.currentContentComponent = 'RegisterDeviceContent';
          break;
        case '我的监控':
          this.currentContentComponent = 'MonitorContent';
          break;
        case '系统信息':
          this.currentContentComponent = 'SystemInformationContent';
          break;
        case '我的设备':
          this.currentContentComponent = 'SearchingDeviceContent';
          break;
        default:
          this.currentContentComponent = null;
      }
      this.isSidebarVisible = false;
    },
    sendData(data) {
      if (this.$refs.header.loading) {
        this.setSnackBarFalse('设备连接中，请稍后重试！')
        return;
      }
      // console.log("---------- receive data ----------")
      // console.log(data)
      window.electronAPI.sendSettings(data);
      // this.setSnackBarTrue('数据发送成功！')
    },
    refresh() {
      const data = {
        "cmd": 246
      }
      const jsonData = JSON.stringify(data);
      window.electronAPI.sendSettings(jsonData);
      this.cpnKey += 1;
      this.setSnackBarTrue("刷新成功");
    },
    setSnackBar(show, color, text, icon, iconColor) {
      this.snackbar.show = show;
      this.snackbar.color = color;
      this.snackbar.text = text;
      this.snackbar.icon = icon;
      this.snackbar.iconColor = iconColor;
    },
    setSnackBarTrue(text) {
      this.setSnackBar(true, 'success', text, 'mdi-check-circle', 'white');
    },
    setSnackBarFalse(text) {
      this.setSnackBar(true, 'error', text, 'mdi-close-circle', 'white');
    },
    transportData(page) {
      let data = {};
      // data = {
      //   "ipaddr": '192.168.2.3',
      //   "mask": '255.255.0.0',
      //   "gateway": '192.168.2.1',
      //   "wlan-name": 'glk',
      //   "wlan-password": 'glk22008030'
      // };
      if (!this.deviceInfo) return;
      else {
        // console.log(this.deviceInfo)
        switch (page) {
          case 'WIFI设置':
            data = this.deviceInfo.wlan;
            break;
          case '端口设置':
            data.serial = this.deviceInfo.serial;
            data.portmap = this.deviceInfo.portmap;
            break;
          default:
            return;
        }
      }
      // console.log(data)
      this.$refs.cpn.receiveData(data);
    },
    debounce(func, wait) {
      let timeout;
      return function (...args) {
        const context = this;
        clearTimeout(timeout);
        timeout = setTimeout(() => {
          func.apply(context, args);
        }, wait);
      }
    },
    setupListener() {
      this.debouncedAutoRefresh = this.debounce(this.refresh, 2000);
    },
    showStatusAlert(devIp) {
      const devName = localStorage.getItem('devName');
      this.dialog = true;
      this.status = 2;
      this.title = `连接设备${devName}`;
      this.message = '连接中';
      this.ip = devIp;
    },
    // 将result去除数据头
    processDataFromServer(result) {
      console.log(result)
      // 提取匹配后的剩余部分
      // console.log(data)
      try {
        // 尝试解析JSON数据
        const jsonData = JSON.parse(result);
        return {
          code: jsonData.response,
          info: jsonData.config
        };
      } catch (error) {
        // 处理JSON解析错误
        console.error('JSON parsing error:', error);
        return false; // 或者根据你的错误处理逻辑返回一个特定的值
      }
    },
    // 发起串口映射请求
    tryPortMapping(port) {
      this.portInfo = Object.entries(port).map(([, value]) => ({'remotePort': value}));
      // this.portInfo = info;
      console.log("receive portInfo from remoteDev");
      console.log(this.portInfo.length)
      if (this.portInfo.length === 0) {
        console.log('没有串口设置')
        this.message = '请前往端口设置进行配置'
        this.status = 1;
        this.$refs.cpn.devices[this.$refs.cpn.hasSwitchOn].switchOn = 0;
        this.$refs.cpn.hasSwitchOn = -1;
      } else {
        const data = {
          "ip": this.ip,
          "portArray": this.portInfo
        }
        window.electronAPI.serialPortMapping(JSON.stringify(data));
        console.log(this.portInfo);
      }
    },
    setReceiveDataFromServerListener() {
      window.electronAPI.serverDataCallback((event, result) => {
        // console.log("---------- receive data ----------")
        // console.log(result);
        const data = this.processDataFromServer(result);
        if (data !== false) {
          switch (data.code) {
            case 224:
              this.setSnackBarTrue('保存成功');
              this.debouncedAutoRefresh();
              break;
            case 225:
              console.error('数据格式错误');
              break;
            case 226:
              this.setSnackBarFalse('配置有误，保存失败！');
              break;
            case 227:
              this.deviceInfo = data.info;
              // console.log("----------device info----------")
              // console.log(this.deviceInfo)
              this.transportData(this.$refs.sb.selectedItem);
              break;
            case 228:
              this.tryPortMapping(data.info.port);
              setTimeout(()=> {
                const data = {
                  "cmd": 246
                }
                window.electronAPI.sendSettings(JSON.stringify(data));
              }, 50);
              this.wifiId = setInterval(() => {
                window.electronAPI.sendSettings(JSON.stringify(this.wifiRequest));
              }, 10000);
              break;
            case 229:
              this.message = '设备无法连接';
              this.status = 1;
              if (this.$refs.cpn.hasSwitchOn !== -1) {
                this.$refs.cpn.devices[this.$refs.cpn.hasSwitchOn].switchOn = 0;
                this.$refs.cpn.hasSwitchOn = -1;
              }
              break;
            case 230:
              console.log("here is 230")
              this.message = '';
              this.portInfo.forEach((p) => {
                if (p.remotePort === 8888) this.message += 'COM11 ';
                if (p.remotePort === 8889) this.message += 'COM12 ';
                if (p.remotePort === 8890) this.message += 'COM13 ';
              });
              this.status = 0;
              window.electronAPI.requestIP();
              this.$refs.header.devName = localStorage.getItem('devName');
              setTimeout(() => {
                window.electronAPI.sendSettings(JSON.stringify(this.networkRequest));
              }, 500);
              this.strengthId = setInterval(() => {
                window.electronAPI.sendSettings(JSON.stringify(this.networkRequest));
              }, 40000);
              break;
            case 231:
              this.$refs.cpn.receiveData(data.info);
              break;
            case 232:
              this.$refs.cpn.status = 'fail';
              break;
            case 233:
              this.$refs.cpn.status = 'success';
              break;
            case 234:
              this.$refs.header.setNetwork(data.info)
              break;
            case 235:
              console.log(data.info);
              this.wifiList = data.info["wifi-list"];
              if (this.$refs.sb.selectedItem === 'WIFI设置')
                this.$refs.cpn.getWifi(this.wifiList);
              break;
            default:
              break;
          }
        }
      });
    },
    setSendDataCallbackListener() {
      window.electronAPI.sendSettingsCallback((event, data) => {
        console.log(data)
        if (data === 'devClient') {
          if (this.$refs.sb.selectedItem === '系统信息') this.$refs.cpn.status = 'checkFailed';
        }
        if (data === 'client') {
          this.setSnackBarFalse('设备未连接')
          this.connected = false;
        }
      });
    },
    setConnRemoteCallbackListener() {
      window.electronAPI.connRemoteCallback((event, result) => {
        console.log(result);
        if (result === 'failed to connect') {
          this.message = '设备无法连接';
          this.status = 1;
          console.log(this.$refs.cpn.hasSwitchOn)
          this.$refs.cpn.devices[this.$refs.cpn.hasSwitchOn].switchOn = 0;
          this.$refs.cpn.hasSwitchOn = -1;
        }
        localStorage.removeItem('devName');
        this.$refs.header.devName = '';
        this.$refs.header.setNetwork([]);
        clearInterval(this.strengthId);
        clearInterval(this.wifiId);
      });
    },
    setConnectServerCallbackListener() {
      window.electronAPI.connectServerCallback((event, result) => {
        console.log(result)
        const stat = result.toString().split('-')[0];
        const code = result.toString().split('-')[1];
        if (stat === '1') this.setSnackBarFalse(resultErrCode[parseInt(code)]);
        else {
          switch (code) {
            case '2':
              this.connected = true;
              this.setSnackBarTrue(resultSuccessCode[parseInt(code)]);
              setTimeout(() => {
                const data = {
                  "cmd": 246
                }
                const jsonData = JSON.stringify(data);
                window.electronAPI.sendSettings(jsonData);
              }, 1000);
              break;
            case '3':
              this.$refs.cpn.disconnectRemoteCallback();
              break;
            default:
              break;
          }
        }
        if (stat === '1' || code === '2') this.$refs.header.connectEnd()
      });
    },
    toggleSidebar() {
      this.isSidebarVisible = !this.isSidebarVisible;
    },
    checkWindowWidth() {
      if (window.innerWidth > 1000) {
        this.isSidebarVisible = false;
      }
    },
  }
}
</script>

<style scoped>
.home {
  display: flex;
  flex-direction: column;
  height: 100vh;
  border-radius: 5px;
}

header {
  height: 60px;
}

.main-content {
  display: flex;
  flex: 1;
}

.ad-carousel {
  width: calc(100vw - 216px);
  margin-left: 200px;
  margin-top: -100px;
  flex-shrink: 0; /* 固定高度，不影响主内容区 */
}

.sidebar {
  width: 200px;
  transition: transform 0.3s ease;
}

/* 在小于1000px时隐藏侧边栏 */
@media (max-width: 1100px) {
  .sidebar {
    transform: translateX(-100%); /* 隐藏侧边栏 */
    position: absolute; /* 使其可以覆盖其他组件 */
    top: 60px;
    left: 0;
    height: 100%;
    z-index: 1000; /* 确保在最上层 */
  }

  .sidebar.show {
    transform: translateX(4px); /* 显示侧边栏 */
  }
  .toggle-button.show {
    transform: translateX(200px); /* 显示侧边栏 */
  }

  .toggle-button {
    display: block; /* 在小屏幕下显示按钮 */
    top: 70px;
  }
}

/* 大于1000px时按钮隐藏 */
@media (min-width: 1101px) {
  .toggle-button {
    display: none; /* 隐藏按钮 */
  }
}
.toggle-button {
  position: absolute;
  width: 30px;
  height: 30px;
  background: #1976d2; /* 背景透明 */
  border: none; /* 去掉边框 */
  font-size: 20px; /* 调整按钮字体大小 */
  cursor: pointer;
  color: white;
  transition: transform 0.3s ease;
  border-radius: 5px;
  z-index: 1000;
}
.overlay {
  background: rgba(0, 0, 0, 0);
  z-index: 999; /* 确保在侧边栏之上 */
  transition: background 0.3s ease;
}
.overlay2 {
  position: fixed; /* 覆盖整个窗口 */
  top: 0;
  left: 204px;
  right: 0;
  bottom: 0;
  z-index: 999; /* 确保在侧边栏之上 */
  background: rgba(0, 0, 0, 0.5); /* 半透明黑色 */
  transition: background 0.3s ease;
}
</style>
